<?php



namespace App\Http\Controllers\Api\Test;


use App\Http\Controllers\Api\BasicController;
use App\Models\Mental\Lists;
use App\Models\Mental\Logs;
use App\Models\Mental\Topic;
use App\Models\Mental\Type;
use Jiannei\Response\Laravel\Support\Facades\Response;

class MentalController extends BasicController
{

    /**
     * @api {post }  /test/mental/types
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\Resources\Json\JsonResource|\Jiannei\Response\Laravel\JsonResource|\Jiannei\Response\Laravel\JsonResponse
     */

    public function types(){
        $result =Type::all();
        return Response::success($result);

    }

    /**
     * @api {post }  /test/mental/recommend
     */
    public function recommend(){
        if($this->request->input('change')==1){
            $result =Lists::query()->where(['is_recommend'=>1])->orderBy('order','desc')->skip(4)->inRandomOrder()->take(4)->get();
        }else{
            $result =Lists::query()->where(['is_recommend'=>1])->orderBy('order','desc')->limit(4)->get();
        }
        return Response::success($result);

    }

    /**
     * @api {post }  /test/mental/index
     */
    public function index(){
        if($this->request->input('free')==1){
            $result =Lists::query()->where(['price'=>0])->orderBy('id','desc')->limit(4)->get();
        }else{
            $result =Lists::query()->where('price','>',0)->orderBy('id','desc')->limit(4)->get();
        }
        return Response::success($result);
    }

    /**
     * @api {post }  /test/mental/list
     */
    public function list(){
        $type_id = $this->request->input('type_id');
        $sk = $this->request->input('sk');
        $where=[];
        if($type_id) $where['type_id']=$type_id;
        $query =Lists::query()->where($where);
        if($sk){
            $query->where('title','like',"%{$sk}%");
        }
        $result=$query->paginate(10);
        return Response::success($result);
    }

    public function start(){

        $test_id =  $this->request->input('test_id');
        $uid = $this->uid();
        $result = (new Lists())->start($uid,$test_id);
        return Response::success($result);
    }


    public function topics(){
        $order_id =  $this->request->input('order_id');
        $test_id=Logs::where(['id'=>$order_id,'user_id'=>$this->uid(),'pay'=>1])->pluck('list_id')->first();
        if(!$test_id) return Response::fail('获取失败');
        $result=Topic::where(['list_id'=>$test_id])->with('options')->get();
        return Response::success($result);
    }

    public function end(){
        $log_id =  $this->request->input('order_id');
        $score =  $this->request->input('score');
        $uid = $this->uid();
        $result = (new Lists())->end($uid,$log_id,$score);
        return Response::success($result);
    }

}
